/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/* 平铺的数组转树形结构 */
export const transitionToTreeData = (list, pid = '') => list.filter(item => item.pid === pid).map(item => {
  return { ...item, children: transitionToTreeData(list, item.id) }
})

export const transToTreeData = (list, rootValue) => {
  const array = []
  list.forEach(item => {
    if (item.pid === rootValue) {
      const children = transToTreeData(list, item.id)
      if (children.length) {
        item.children = children
      }
      array.push(item)
    }
  })
  return array
}

export const formatExcelDate = (number, format = '/') => {
  let time = new Date((number - 25567) * 24 * 3600000 - 5 * 60 * 1000 - 43 * 1000 - 24 * 3600000 - 8 * 3600000)
  time.setFullYear(time.getFullYear())
  let year = time.getFullYear() + ''
  let month = time.getMonth() + 1 + ''
  let date = time.getDate() + ''
  if (format && format.length === 1) {
    return year + format + month + format + date
  }
  return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}

/*
导入的数据中文key转换为英文
思路：对于原数组每个对象来说
(1） 找出所有的中文key
(2)  得到对应的英文key
(3)  拼接一个新对象： 英文key:值
 */
export const transitionExcelHeaderToEnKey = (results) => {
  // 首先需要一个我们写好的用来映射的对象或数组
  const mapInfo = {
    '入职时间': 'timeOfEntry',
    '手机号': 'mobile',
    '员工姓名': 'username',
    '转正时间': 'correctionTime',
    '工号': 'workNumber',
    '部门名称': 'departmentName',
    '聘用形式': 'formOfEmployment',
    '头像': 'staffPhoto',
    '账户状态': 'enableState',
    'id': 'id',
    '密码': 'password'
  }

  return results.map(zhObj => {

    // 首先创建一个空对象来逐个接收转换后的key
    const enObj = {}

    // 使用Object.keys方法来获取中文的key
    const zhKeys = Object.keys(zhObj) // ['姓名', '手机号']

    // 用forEach循环来将key逐个映射(map)出去
    zhKeys.forEach(zhKey => {
      const enKey = mapInfo[zhKey] // 如果是一个对象具体的某个属性,就用 对象.(属性),此处非确切值,则为 对象[属性] 写法
      if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
        enObj[enKey] = new Date(formatExcelDate(zhObj[zhKey]))
      } else {
        enObj[enKey] = zhObj[zhKey] // 将空对象所需要接收的值传入
      }
    })

    return enObj
  })
}
